import {
  Controller,
  Get,
  Post,
  Delete,
  Param,
  HttpCode,
  HttpStatus,
  UseGuards,
  UseInterceptors,
  UploadedFile,
  Query,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiConsumes,
  ApiBody,
} from '@nestjs/swagger';
import { FileInterceptor } from '@nestjs/platform-express';
import { ImageService } from './image.service';
import type { Image } from './image.service';
import type { Multer } from 'multer';

@ApiTags('图片管理')
@Controller('images')
export class ImageController {
  constructor(private readonly imageService: ImageService) {}

  @ApiOperation({ summary: '获取图片列表' })
  @ApiResponse({ status: 200, description: '成功获取图片列表' })
  @Get()
  findAll(): Image[] {
    return this.imageService.findAll();
  }

  @ApiOperation({ summary: '根据ID获取图片详情' })
  @ApiResponse({ status: 200, description: '成功获取图片详情' })
  @ApiResponse({ status: 404, description: '图片不存在' })
  @Get(':id')
  findOne(@Param('id') id: string): Image {
    const image = this.imageService.findById(id);
    if (!image) {
      throw new Error('Image not found');
    }
    return image;
  }

  @ApiOperation({ summary: '上传图片' })
  @ApiResponse({ status: 201, description: '图片上传成功' })
  @ApiConsumes('multipart/form-data')
  @ApiBearerAuth()
  @ApiBody({
    description: '上传图片文件',
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @UseInterceptors(FileInterceptor('file'))
  @Post('upload')
  @HttpCode(HttpStatus.CREATED)
  uploadFile(
    @UploadedFile() file: Multer.File,
    @Query('userId') userId: string,
  ): Image {
    if (!file) {
      throw new Error('No file provided');
    }
    return this.imageService.saveImage(file, userId);
  }

  @ApiOperation({ summary: '删除图片' })
  @ApiResponse({ status: 204, description: '图片删除成功' })
  @ApiResponse({ status: 404, description: '图片不存在' })
  @ApiBearerAuth()
  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  remove(@Param('id') id: string): void {
    const result = this.imageService.delete(id);
    if (!result) {
      throw new Error('Image not found');
    }
  }

  @ApiOperation({ summary: '获取用户上传的图片' })
  @ApiResponse({ status: 200, description: '成功获取用户图片' })
  @ApiBearerAuth()
  @Get('user/:userId')
  getUserImages(@Param('userId') userId: string): Image[] {
    return this.imageService.findByUserId(userId);
  }
}